package com.cysion.study.ui.personal

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.os.StrictMode
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.other.color
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.R
import com.cysion.study.entity.AddressBean
import com.cysion.study.entity.AddressInfoPO
import com.cysion.study.entity.UserEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.widget.*
import com.cysion.study.widget.http.HttpUtil
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import kotlinx.android.synthetic.main.activity_personal.*
import org.json.JSONObject
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

//个人信息  未使用
class PersonalActivity : BaseActivity(), View.OnClickListener, PicChooserDialog.OnPicChooserListener {


    var userInfo: UserEntity? = null
    override fun getLayoutId(): Int = R.layout.activity_personal

    override fun initView() {
        initPhotoError()
       /* whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("个人资料")
            setLeftImg()
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        topbar.setLeftImg(R.mipmap.icon_back)*/

        darkTextTheme(color(R.color.main_cl))
        /*topbar.apply {
            setTitle("个人资料")
            setLeftImg(R.mipmap.icon_back)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }*/

        topbar.apply {
            setTitle("个人资料")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }


        iv_head.setOnClickListener(this)
        tv_name.setOnClickListener(this)
        tv_brithday.setOnClickListener(this)
        tv_area.setOnClickListener(this)
        tv_address.setOnClickListener(this)
        tv_sex.setOnClickListener(this)
        iv_bg.setOnClickListener(this)

        //获取日历的一个对象
        cal = Calendar.getInstance()
        //获取年月日时分秒的信息
        year = cal.get(Calendar.YEAR)
        //month从0开始计算(一月month = 0)
        month = cal.get(Calendar.MONTH) + 1
        day = cal.get(Calendar.DAY_OF_MONTH)
        hour = cal.get(Calendar.HOUR_OF_DAY)
        minute = cal.get(Calendar.MINUTE)
    }

    private fun initPhotoError() {
        // android 7.0系统解决拍照的问题
        var builder =  StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }


    override fun initData() {
        super.initData()
        getUserInfo()
        loadProviceData()
    }

    private fun loadProviceData() {
        ApiClient.api.getAllCity(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    pcaCodeList = it
                }
                _onError {

                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private var userBean: UserEntity? = null

    private fun getUserInfo() {
        Alert.loading(self)
        ApiClient.api.getUserInfos(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    userBean = it
                    UserCache.save(it)
                    initUser()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private fun initUser() {
        userInfo = UserCache.userInfo
        /*{"status":"SUCCESS","msg":"","data":{"birthday":"","address":"","city":"","nickName":"18628178473"
            ,"headImageUrl":"","sex":0,"type":0,"isHasPayPassword":1,"province":"","money":388.00
            ,"phone":"18628178473","id":1,"backImageUrl":""},"code":0,"count":0}*/
        /*Glide.with(context).load(UserCache.userInfo?.avatar ?: R.mipmap.default_head)
            .apply(RequestOptions.circleCropTransform())
            .into(iv_head)*/
        Glide.with(iv_head.context).load(UserCache.userInfo?.headImageUrl).apply(
            RequestOptions().placeholder(R.mipmap.default_head)
        ).into(iv_head)
        Glide.with(iv_head.context).load(UserCache.userInfo?.backImageUrl).apply(
            RequestOptions().placeholder(R.mipmap.default_head)
        ).into(iv_bg)
        tv_name.text = UserCache.userInfo?.nickName
        //性别 0.未知 1.男 2.女
        if (UserCache.userInfo?.sex == 0) {
            tv_sex.text = "未知"
        } else if (UserCache.userInfo?.sex == 1) {
            tv_sex.text = "男"
        } else if (UserCache.userInfo?.sex == 2) {
            tv_sex.text = "女"
        }
        if (TextUtils.isEmpty(UserCache.userInfo?.birthday)) {
            tv_brithday.text = "请选择出生日期"
        } else {
            tv_brithday.text = UserCache.userInfo?.birthday
        }

        if (TextUtils.isEmpty(UserCache.userInfo?.address)) {
            tv_address.text = "请填写详细地址"
        } else {
            tv_address.text = UserCache.userInfo?.address
        }

        if (TextUtils.isEmpty(UserCache.userInfo?.city)) {
            tv_area.text = "请选择城市"
        } else {
            tv_area.text = UserCache.userInfo?.province + UserCache.userInfo?.city

        }


    }

    private var isHead: Boolean = true

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_head -> {
                isHead = true
                takePhoto()
            }
            R.id.iv_bg -> {
                isHead = false
                takePhoto()
            }
            R.id.tv_name -> {
                editContent()
            }
            R.id.tv_sex->{
                Alert.selectSex(this, "", "", "", "确定") { confirm, type ->
                    if (TextUtils.isEmpty(type)) {
                        ShowToast("请选择性别")
                        return@selectSex
                    }

                    if (confirm == CONFIRM) {
                        Alert.close()
                        //type=1男  =2女
                        if (type == "1") {
                            sex = "1"
                            tv_sex.text = "男"
                        } else if (type == "2") {
                            sex = "2"
                            tv_sex.text = "女"
                        }
                        userInfo?.sex = sex.toInt()
                        UserCache.save(userInfo)
                        updateUser()
                    }
                }
            }
            R.id.tv_brithday->{
                dialog()
            }
            R.id.tv_area->{//修改省市
                //条件选择器
                initAddressPicker(pcaCodeList)
            }
            R.id.tv_address -> {
                editAddress()
            }
        }
    }

    fun takePhoto() {
        val dialog = PicChooserDialog(this, R.style.bottom_dialog)
        dialog.setListner(this)
        dialog.show()
    }

    //img start  以下两个回调方法 是选择图片和拍照回调
    override fun onClickFromGallery(view: View?) {
        startImagePick()
    }

    override fun onClickFromCamera(view: View?) {
        startActionCamera()
    }
    //img end
    /**
     * 选择图片裁剪
     *
     */
    private fun startImagePick() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(
            Intent.createChooser(intent, "选择图片"), 10
        )
    }




    private var imageName: String? = null
    /**
     * 相机拍照
     *
     */
    private fun startActionCamera() {
        val SAVE_PIC_PATH = Environment.getExternalStorageDirectory().absolutePath + "/Buyers/saveImage/"

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val dir = File(SAVE_PIC_PATH)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        imageName = SAVE_PIC_PATH + getNowTime() + ".png"

        val file = File(imageName!!)
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {

            }

        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
        startActivityForResult(intent, 11)//FileUriExposedException: file:///storage/emulated/0/Buyers/saveImage/080801163759.png exposed beyond app through ClipData.Item.getUri()
    }

    private var protraitPath: String? = null
    private var protraitFile: File? = null
    private var protraitBitmap: Bitmap? = null
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (Activity.RESULT_OK == resultCode) {
            when (requestCode) {
                10->{//
                    val uri = data!!.data
                    if (uri != null) {
                        protraitPath = getAbsoluteImagePath(this, uri)
                        protraitFile = File(protraitPath)
                        //outputBitmap(null,ImageUtils.getAbsoluteImagePath(this, uri));
                    }
                    if (uri == null) {
                        //use bundle to get data
                        val bundle = data.extras
                        if (bundle != null) {
                            val photo = bundle.get("data") as Bitmap //get bitmap
                            //spath :生成图片取个名字和路径包含类型
                            setBitmapTempFile(photo)

                        } else {
                            ShowToast("获取图片错误")
                            return
                        }
                    }
                    // 获取头像缩略图
                    if (!TextUtils.isEmpty(protraitPath) && protraitFile!!.exists()) {
                        protraitBitmap = ImageUtils.getBitmapByPath(protraitPath)
                        protraitPath = compressImage(protraitPath.toString())
                        outputBitmap(protraitBitmap!!, protraitPath!!)
                    }
                }
                11->{
                    if (imageName != null) {
                        val degree = PhotoUtils.readPictureDegree(imageName)
                        val bitmap = FileCompressUtil.com(imageName)
                        if (bitmap != null) {
                            val newbitmap = PhotoUtils.rotaingImageView(
                                degree,
                                bitmap
                            )
                            val mCompressPhotopath = PhotoUtils.saveBitmap2file(
                                newbitmap, System.currentTimeMillis().toString() + ".jpg"
                            )
                            if (TextUtils.isEmpty(mCompressPhotopath)) {
                                return
                            }
                            val file = File(mCompressPhotopath)
                            //                            updateAvatarInServer(file);
                            protraitBitmap = ImageUtils.getBitmapByPath(mCompressPhotopath)
                            outputBitmap(protraitBitmap!!, mCompressPhotopath)
                        }

                    }
                }
            }

        }
    }

    fun outputBitmap(bitmap: Bitmap, path: String) {
        println("#####选择图片=" + path)
        if (TextUtils.isEmpty(path)) {
            return
        }
        headUrl = path
        uploadPic(File(headUrl))
    }

    private fun uploadPic(headUrl: File) {
        val params = RequestParams()
        params.put("file", headUrl)
        params.put("token", ACache.get(Box.context).getAsString("token"))
        HttpUtil.post1(Urls.uploadPicture, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
                    if (response?.getString("code") == "0") {
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        if (isHead) {
                            userBean?.headImageUrl = response.getString("data")
                        } else {
                            userBean?.backImageUrl = response.getString("data")
                        }
                        updateUser()
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    Alert.close()
//                    ShowDialog.dissmiss()
                }
            }
            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                Alert.close()
            }
        })
    }

    fun compressImage(picFileName: String): String {
        val bitmap = BitmapUtil.decodeFile(picFileName, 960)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        var options = 90f
        while (baos.toByteArray().size / 1024 > 200 && options > 80) { // 循环判断如果压缩后图片
            baos.reset()// 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options.toInt(), baos)// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5f// 每次都减少10
        }
        val file = FileUtils.createFileWithSuffix(".jpg", this)
        println("压缩后大小 " + baos.toByteArray().size / 1024 + "==options=" + options)
        // 保存新文件
        try {
            val out = FileOutputStream(file)
            out.write(baos.toByteArray())
            out.flush()
            out.close()
            return file.getAbsolutePath()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return ""
        } catch (e: IOException) {
            e.printStackTrace()
            return ""
        }
    }


    private val  FILE_SAVEPATH: String = Environment.getExternalStorageDirectory().absolutePath
    private var cropUri: Uri? = null
    private var origUri: Uri? = null
    private fun setBitmapTempFile(bitmap: Bitmap): Uri? {
        val storageState = Environment.getExternalStorageState()
        if (storageState == Environment.MEDIA_MOUNTED) {
            val savedir = File(FILE_SAVEPATH)
            if (!savedir.exists()) {
                savedir.mkdirs()
            }
        } else {
            ShowToast("无法保存上传的头像，请检查SD卡是否挂载")
            return null
        }
        val timeStamp = SimpleDateFormat("yyyyMMddHHmmss")
            .format(Date())
        // 照片命名
        val cropFileName = "osc_camera_$timeStamp.jpg"
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName
        protraitFile = File(protraitPath)
        try {
            ImageUtils.saveImage(this, protraitPath, bitmap)
        } catch (e: IOException) {
            e.printStackTrace()
        }

        cropUri = Uri.fromFile(protraitFile)
        this.origUri = this.cropUri
        return this.cropUri
    }

    /**
     * 通过uri获取文件的绝对路径
     *
     * @param uri
     * @return
     */
    fun getAbsoluteImagePath(context: Activity, uri: Uri): String {
        var imagePath = ""
        val proj = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = context.managedQuery(uri, proj, null, null, null)// Which columns to
        if (cursor != null) {
            val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            if (cursor.count > 0 && cursor.moveToFirst()) {
                imagePath = cursor.getString(column_index)
            }
        }

        return imagePath
    }

    //获取当前时间
    @SuppressLint("SimpleDateFormat")
    private fun getNowTime(): String {
        val date = Date(System.currentTimeMillis())
        val dateFormat = SimpleDateFormat("MMddHHmmssSS")
        return dateFormat.format(date)
    }



    private fun editAddress() {
        val view = Alert.setup(this, R.layout.dialog_comment, 0.8f, false, null)
        val tv_title = view.findViewById<TextView>(R.id.tv_title)
        tv_title.text = "地址"
        val editor = view.findViewById<TextView>(R.id.etComment)
        editor.hint = "请输入详细地址"
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            Alert.close()
//            clickListener?.invoke(CANCEL, "")
        }
        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (TextUtils.isEmpty(editor.text.toString().trim())) {
                ShowToast("请输入内容")
                return@setOnClickListener
            }
            Alert.close()
//            clickListener?.invoke(CONFIRM, editor.text.toString().trim())
            userInfo?.address = editor.text.toString().trim()
            UserCache.save(userInfo)
            updateUser()
        }
    }
    private var sex = ""
    private lateinit var pcaCodeList: List<AddressBean>


    private fun editContent() {
        val view = Alert.setup(this, R.layout.dialog_comment, 0.8f, false, null)
        val tv_title = view.findViewById<TextView>(R.id.tv_title)
        tv_title.text = "昵称"
        val editor = view.findViewById<TextView>(R.id.etComment)
        editor.hint = "请输入昵称"
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            Alert.close()
//            clickListener?.invoke(CANCEL, "")
        }
        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (TextUtils.isEmpty(editor.text.toString().trim())) {
                ShowToast("请输入内容")
                return@setOnClickListener
            }
            Alert.close()
//            clickListener?.invoke(CONFIRM, editor.text.toString().trim())
            userInfo?.nickName = editor.text.toString().trim()
            UserCache.save(userInfo)
            updateUser()
        }
    }

    private fun updateUser() {
        Alert.loading(self)
        ApiClient.api.setInfo(
            UserCache.token,
            UserCache.userInfo!!.nickName,
            UserCache.userInfo!!.backImageUrl,
            UserCache.userInfo!!.headImageUrl,
            UserCache.userInfo!!.birthday,
            UserCache.userInfo!!.city,
            UserCache.userInfo!!.province,
            UserCache.userInfo!!.address,
            UserCache.userInfo!!.sex.toString()
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    getUserInfo()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    // * 初始化地址数据
    private fun initAddressPicker(pcaCodeList: List<AddressBean>) {
        val provinceItems = mutableListOf<AddressInfoPO>()
        val cityItems = mutableListOf<MutableList<AddressInfoPO>>()
        val areaItems = mutableListOf<MutableList<MutableList<AddressInfoPO>>>()
        //Json2Bean
//        val pcaCodeList = Gson().fromJson<MutableList<PCACodePO>>(FileUtil.getAssetsFileText(mApplication, "pcacode.json"), object : TypeToken<MutableList<PCACodePO>>() {}.type)
        //遍历省
        pcaCodeList.forEach { pcaCode ->
            //存放省内市区
            val cityList = mutableListOf<AddressInfoPO>()
            //存放省内所有辖区
            val areaList = mutableListOf<MutableList<AddressInfoPO>>()
            //遍历省内市区
            pcaCode.citys.forEach { cCode ->
                //添加省内市区
                cityList.add(AddressInfoPO(cCode.id, cCode.name))
                //存放市内辖区
                val areas = mutableListOf<AddressInfoPO>()
                //添加市内辖区
                cCode.countys.forEach { addressInfo ->
                    areas.add(AddressInfoPO(addressInfo.id, addressInfo.name))
                }
                areaList.add(areas)
            }
            //添加省份
            provinceItems.add(AddressInfoPO(pcaCode.id, pcaCode.name))
            //添加市区
            cityItems.add(cityList)
            //添加辖区
            areaItems.add(areaList)
        }
        //显示选择器
        showAddressPicker(provinceItems, cityItems, areaItems)
    }


    /**
     * 显示地址选择
     */
    fun showAddressPicker(
        provinceItems: MutableList<AddressInfoPO>,
        cityItems: MutableList<MutableList<AddressInfoPO>>,
        areaItems: MutableList<MutableList<MutableList<AddressInfoPO>>>
    ) {
        //条件选择器
        val pvOptions = OptionsPickerBuilder(this@PersonalActivity,
            OnOptionsSelectListener { options1, option2, options3, v ->
                //返回的分别是三个级别的选中位置
                var tx = ""
                println("####区数据1${areaItems[options1][option2].size}")
                if (areaItems[options1][option2].size < 11) {
                    tx = provinceItems[options1].pickerViewText + cityItems[options1][option2].pickerViewText
                } else {
                    tx =
                        provinceItems[options1].pickerViewText + cityItems[options1][option2].pickerViewText + areaItems[options1][option2][options3].pickerViewText
                }
                tv_area.text = tx//山东省AddressInfoPO(id=2, name=济南2)章丘
                println("####$tx")
                userInfo?.province = provinceItems[options1].pickerViewText
                userInfo?.city = cityItems[options1][option2].pickerViewText
                UserCache.save(userInfo)
                updateUser()
            }).build<AddressInfoPO>()
        pvOptions.setPicker(provinceItems, cityItems, areaItems)
        pvOptions.show()
    }


    private var birthday = ""
    private var headUrl = ""
    lateinit var cal: Calendar
    var year: Int = 0
    var month: Int = 0
    var day: Int = 0
    var hour: Int = 0
    var minute: Int = 0
    private fun dialog() {
        val dateDialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { dp, year, month, dayOfMonth ->
                //2017-12-04 12：00：00
                birthday =
                    year.toString() + "-" + (if (month + 1 < 10) "0" + (month + 1) else month + 1) + "-" + if (dayOfMonth < 10) "0$dayOfMonth" else dayOfMonth
//                age = getCurrentAgeByBirthdate(birthday).toString()
                tv_brithday.text = birthday
                userInfo?.birthday = birthday
                UserCache.save(userInfo)
                updateUser()

            }, year, cal.get(Calendar.MONTH), day
        )
        dateDialog.setTitle("请选择日期")
        dateDialog.show()
    }
    override fun closeMvp() {
    }

}
